package net.togogo.controller;
import com.alibaba.fastjson.JSON;
import net.togogo.bean.Bill;
import net.togogo.bean.User;
import net.togogo.service.BillService;
import net.togogo.util.Contra;
import net.togogo.util.PageUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/bill")
public class BillController {

    @Autowired
    @Qualifier("billService")
    BillService billService;

    //在controller执行之前执行,进行数据的绑定
    @ModelAttribute
    public void huixuan(Bill bill, Model model) {
        model.addAttribute("paramMap", bill);
    }


    @RequestMapping("/billList")
    public String billList(Model model, HttpSession session,
                           @RequestParam(value = "pageNo", required = false) String pageNos,
                           Bill bill) {
        //System.out.println("页面传递进来的值=======>"+bill.toString());

        int pageNo = 1;
        int pageSize = 2;
        //查询出bill有多少条数据
        int billCount = billService.selectBillCount(bill);
        PageUtil pageUtil = new PageUtil();
        pageUtil.setPageNo(pageNo);
        pageUtil.setPageSize(pageSize);
        pageUtil.setTotalCount(billCount);
        int totalPageCount = pageUtil.getTotalPageCount();
        if (pageNos != null) {
            int pos = Integer.parseInt(pageNos);
            if (pos <= 0) {
                pageNo = 1;
            } else if (pos > totalPageCount) {
                pageNo = totalPageCount;
            } else {
                pageNo = pos;
            }
            if (totalPageCount == 0) {
                pageNo = 1;
            }
        }

        //进行分页查询
        List<Bill> billList = billService.selectBillByLimit(pageNo, pageSize, bill);
        model.addAttribute("billList", billList);
        Map map = new HashMap();
        map.put("pageNo", pageNo);
        map.put("pageSize", pageSize);
        map.put("totalCount", billCount);
        map.put("totalPageCount", totalPageCount);
        model.addAttribute("pages", map);
//        //回显参数  通过@ModelAttribute进行改进
//        Map paramMap = new HashMap();
//        paramMap.put("productName",bill.getProductName());
//        paramMap.put("providerId",bill.getProviderId());
//        paramMap.put("isPayment",bill.getIsPayment());
//        model.addAttribute("paramMap",paramMap);
        return "billList";
    }


    //跳转添加账单
    @RequestMapping(value = "/billAdd",
            method = RequestMethod.GET)
    public String billAdd(Bill bill) {
        return "billAdd";
    }

    //保存
    @RequestMapping(value = "/billAdd",
            method = RequestMethod.POST)
    public String billAdd(@Valid Bill bill,
                          BindingResult result,
                          Model model,
                          @RequestParam(value = "attachs", required = false) MultipartFile[] attachs,
                          HttpServletRequest request,
                          HttpSession session) {
        if (result.hasErrors()) {//输入的内容不满足校验
            //停留在提交页面
            return "billAdd";
        }

        String billPicPath = null;
        //String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;
        System.out.println("<==>" + bill);

        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        System.out.println("uploadFile path ============== > " + path);
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadWpError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                System.out.println("uploadFile oldFileName ============== > " + oldFileName);
                String suffix = FilenameUtils.getExtension(oldFileName);//原文件后缀
                System.out.println("uploadFile suffix============> " + suffix);
                int filesize = 500000;
                System.out.println("uploadFile size============> " + attach.getSize());
                if (attach.getSize() > filesize) {//上传大小不得超过 500k
                    request.setAttribute(errorInfo, " * 上传大小不得超过 500k");
                    flag = false;
                } else if (suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("png")
                        || suffix.equalsIgnoreCase("jpeg") || suffix.equalsIgnoreCase("pneg")) {//上传图片格式不正确
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";
                    System.out.println("new fileName======== " + attach.getName());
                    File targetFile = new File(path, fileName);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    try {
                        //保存
                        attach.transferTo(targetFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败！");
                        flag = false;
                    }
                    if (i == 0) {
                        billPicPath = path + File.separator + fileName;//新的文件名
                    }
//                    else if(i == 1){
//                        workPicPath = path+File.separator+fileName;
//                    }


                    } else {
                        request.setAttribute(errorInfo, " * 上传图片格式不正确");
                        flag = false;
                    }
                }
            }
            if (flag) {
                bill.setCreationDate(new Date());
                bill.setCreatedBy(((User)session.getAttribute(Contra.USER_SESSION)).getId());
                bill.setBillPic(billPicPath);
                // user.setWorkPicPath(workPicPath);
                System.out.println("============================>"+bill.toString());
                if (billService.insertBill(bill)) {
                    return "redirect:/bill/billList";
                }
            }

        return "billAdd";
    }



    //{id} 占位符
    @RequestMapping("/billShow/{id}")
    @ResponseBody
    public String billShow(@PathVariable String id,Model model){

        System.out.println("页面传递来的ID======>"+id);

        Bill bill = billService.selectBillById(id);
        if (bill==null){
            return null;
        }
        return JSON.toJSONStringWithDateFormat(bill,"yyyy-MM-dd HH:mm:ss");
    }

    @PostMapping("/billUpdate")
    @ResponseBody
    public String billUpdate(Bill bill,@RequestParam String providerName,HttpSession session){

        System.out.println(providerName);
        System.out.println(bill);

        User loginUser = (User)session.getAttribute(Contra.USER_SESSION);
        if (loginUser!=null){
            Integer userId = loginUser.getId();
            bill.setModifyBy(userId);
        }

        int i = billService.updateBill(bill);
        if (i!=1){
            return "error";
        }
        return "1";
    }




}
    //局部异常处理的方法  针对当前controller(局部异常处理和全局异常处理不能同时存在)
    /*@ExceptionHandler(value = RuntimeException.class)
    public String error(RuntimeException e, HttpServletRequest request){
        request.setAttribute("message","=====>错误信息:"+e);
        return "error";
    }*/


